package 
{
	import adobe.utils.CustomActions;
	import flash.display.DisplayObject;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.TimerEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.text.StyleSheet;
	import flash.text.TextField;
	import flash.text.TextFormat;
	import flash.utils.Timer;
	import flash.system.System;
	
	import vk.APIConnection;
	import vk.events.*;
	import vkutill.*;
	
	
	/**
	 * ...
	 * @author me
	 */
	public class Main extends Sprite 
	{
		public static var useEmbededContent:Boolean = true;
		
		public static var player:ClShip = null;
		public var scoresText:TextField;
		
		public var txtFirstName:TextField;
		public var txtLastName:TextField;
		public var txtGroupsIds:TextField;
		
		private var insInterface:Interface;
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
			//this.stage.focus = this;
		}
		
		private function hanMeteorAssault(e:TimerEvent):void
		{
			var newMet:ClMeteor = new ClMeteor(this);
			stage.addChild(newMet);
			newMet = null;
		}
		
		public var playerFirstName:String = null;
		public var playerLastName:String = null;
				
		private function getGroupsId_Fail(data:Object):void
		{
			txtGroupsIds.text = "ERROR";
		}
		
		public static var TEST_TYPE:int = 0;
		public static var VK_TYPE:int = 1;
		public var appType:int = VK_TYPE;
		
		
		/* Тестовая инициализация */
		private function TestInit():void
		{
			
		}
		
		// Вспомогательная оболочка ВКонтакте.
		public var VKUser:VKUserData;
		/* Инициализация приложения ВКонтакте */
		private function VKInit():void
		{
			/* Переменные передающиеся при загрузке приложения */
			var flashVars: Object = stage.loaderInfo.parameters as Object;	
			
			/* Если выполняется локально */
			if (!flashVars.api_id)
			{
				flashVars['api_id'] = 2263565;
				flashVars['viewer_id'] = 1880982;
				flashVars['sid'] = "0e1a6722c0a562cf0260106c881a69ba1dec40d9f22b54910080f3b2ea9035";
				flashVars['secret'] = "886996fe4d";
			}
			
			/* Инициализация соединения */
			//var VK:APIConnection = new APIConnection(flashVars);
			var VKUserLoader:VKUserData = new VKUserData(flashVars);
			VKUserLoader.addEventListener(VKUserCustomEvent.UserInfoLoaded, function(e:VKUserCustomEvent):void {
					VKUser = e.vkUserInfo;
					VKUser.removeEventListener(VKUserCustomEvent.UserInfoLoaded, HandleVKUser);
					HandleVKUser(e.vkUserInfo);
				}, false, 0, true);
			
			//trace(VKUser.firstName);
			//txtFirstName.text = VKUser.firstName;
			//if (VKUser.photo)
			//{
				//var ph:DisplayObject = addChild(VKUser.photo);
				//ph.x = 10;
				//ph.y = 70;
			//}
			
			//vkWr = new VKWrapper(VK);
			/* Вызываем метод getProfiles, возвращающий данные пользователя с uids*/
			//VK.api("getProfiles", { uids:flashVars["viewer_id"], fields:"photo,photo_big" }, getUserInfo_Complete, getUserInfo_Fail);
			//VK.api("getGroups", {}, getGroupsId_Complete, getGroupsId_Fail);
		}
		
		/* Все необходимые манипуляции с VKUserData */
		private function HandleVKUser(vku:VKUserData):void
		{
			/* Вывод интерфейса */
			//txtFirstName = vku.firstName + " " + vku.lastName;
			trace("Польователь '" + vku.firstName + " " + vku.nickName + " " + vku.lastName+"'");
			trace("Пол " + vku.sex);
			trace("Город "+ vku.city);
		}
		
		
		
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			addEventListener(Event.ENTER_FRAME, update, false, 0, true);
						
			stage.frameRate = 30;
			
			/* entry point */
			
			switch(appType)
			{
				case TEST_TYPE:
				TestInit();
				break;
				case VK_TYPE:
				VKInit();
				break;
			}
			
			var enemyTimer:Timer = new Timer(2000);
			enemyTimer.start();
			enemyTimer.addEventListener(TimerEvent.TIMER, addEnemy);
			
			var tmrMeteorAssault:Timer = new Timer(4000);
			tmrMeteorAssault.start();
			tmrMeteorAssault.addEventListener(TimerEvent.TIMER, hanMeteorAssault, false, 0, true);
			
			var txtFormat:TextFormat = new TextFormat();
			txtFormat.size = 20;
			
			/* Кол-во занятой памяти */
			scoresText = new TextField();
			addChild(scoresText);
			scoresText.defaultTextFormat = txtFormat;
			scoresText.x = 10;
			scoresText.y = 10;
			scoresText.wordWrap = false;
			scoresText.text = System.totalMemory.toString();
			scoresText.textColor = 0xFF9999;
			
			/* Пользователь */
			txtFirstName = new TextField();
			addChild(txtFirstName);
			txtFirstName.defaultTextFormat = txtFormat;
			txtFirstName.x = 10;
			txtFirstName.y = 40;
			txtFirstName.width = 300;
			txtFirstName.wordWrap = false;
			//txtFirstName.text = System.totalMemory.toString();
			txtFirstName.textColor = 0xFF9999;
				
			/* Объект караблик */
			player = new ClShip(this);
			
			/* Создание фона */
			FillWithStars(50);
						
			//txtFirstName.text = "apiid:"+flashVars['api_id']+" viewer_id:"+flashVars['viewer_id']+" sid:"+flashVars['sid']+" secret:"+flashVars['secret'];
			//tf.appendText("flashVars['api_id'] = " + flashVars['api_id'] + ";\n");
			//tf.appendText("flashVars['viewer_id'] = " + flashVars['viewer_id'] + ";\n");
			//tf.appendText("flashVars['sid'] = \"" + flashVars['sid'] + "\";\n");
			//tf.appendText("flashVars['secret'] = \"" + flashVars['secret'] + "\";\n");
		}
				
		private function update(e:Event):void
		{
			//scoresText.text = System.totalMemory.toString();
		}
		
		/* Добавление вражины */
		private function addEnemy(e:TimerEvent):void
		{
			if (ClEnemy.EnemyArray.length > 5)	return;
			var en:ClEnemy = new ClEnemy(this);
			en.Behavior = ClEnemy.GetRandBehavior();
			en.targetObject = player;
			en = null;
		}
		
		/* Добавим звёздочек */
		public function FillWithStars(c:int):void
		{
			var i:int;
			var newStar:ClStar;
			/* Мелкие */
			for (i=0; i<c*2; i++)
			{
				newStar = new ClStar(this);
				newStar.x = Math.round(Math.random()*stage.stageWidth);
				newStar.y = Math.round(Math.random()*stage.stageHeight);
				newStar.scaleX=Math.random()/5;
				newStar.scaleY=newStar.scaleX;
				newStar.speedPower = newStar.scaleX*10;
				stage.addChildAt(newStar, 1);
			}
			/* Покрупнее */
			for (i=0; i<c; i++)
			{
				newStar = new ClStar(this);
				newStar.x = Math.round(Math.random()*stage.stageWidth);
				newStar.y = Math.round(Math.random()*stage.stageHeight);
				newStar.scaleX=Math.random();
				newStar.scaleY=newStar.scaleX;
				newStar.speedPower = newStar.scaleX*15;
				stage.addChildAt(newStar, 1);
			}
			
			newStar = null;
		}
		
	}
	
}